package com.redstar.HappyRefresh.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.redstar.HappyRefresh.audit.VideoPublishAuditService;
import com.redstar.HappyRefresh.cache.UserInfo;
import com.redstar.HappyRefresh.limit.Limit;
import com.redstar.HappyRefresh.pojo.BasePage;
import com.redstar.HappyRefresh.pojo.Result;
import com.redstar.HappyRefresh.pojo.Video;
import com.redstar.HappyRefresh.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/luckyjourney/video")
public class VideoController {

    @Autowired
    private VideoService videoService;
    @Autowired
    private QiNiuFileService qiNiuFileService;
    @Autowired
    private VideoPublishAuditService videoPublishAuditService;
    @Autowired
    private FollowService followService;
    @Autowired
    private FeedService feedService;

    @GetMapping("/token")
    public Result getToken() { // 获取视频文件上传的token
        String token = qiNiuFileService.getToken();
        if (token == null) {
            return Result.fail().message("token获取失败");
        }
        return Result.succeed().data(token);
    }

    @PostMapping
//    @Limit(limit = 5, time = 3600L, msg = "发布视频一小时内不可超过5次")
    public Result publishVideo(@RequestBody @Validated Video video) { // 发布视频或修改视频
        String message = videoService.publishVideo(video);
        if ("success".equals(message)) {
            return Result.succeed().message("发布成功，请等待审核");
        } else {
            log.error("publishVideo方法：" + message);
            return Result.fail().message(message);
        }
    }

    @DeleteMapping("/{id}")
    public Result deleteVideo(@PathVariable Long id) { // 删除视频
        if (ObjectUtils.isEmpty(id)) {
            log.error("deleteVideo方法：id为null，你让我删个锤子");
            return Result.fail().message("id为null，你让我删个锤子");
        }
        String message = videoService.deleteVideo(id);
        if ("success".equals(message)) {
            return Result.succeed().message("视频删除成功");
        } else{
            log.error("deleteVideo方法：" + message);
            return Result.fail().message(message);
        }
    }

    @GetMapping
    public Result listVideo(BasePage basePage) { // 查看用户管理的视频-稿件管理，分页
        Long userId = UserInfo.get();
        IPage<Video> videoPage = videoService.listByUserIdVideo(basePage, userId);
        if (ObjectUtils.isEmpty(videoPage)) {
            log.info("listVideo方法：用户的稿件为null");
        }
        return Result.succeed().data(videoPage);
    }

    @PostMapping("/star/{id}")
    public Result starVideo(@PathVariable Long id) { // 点赞视频/取消点赞
        if (ObjectUtils.isEmpty(id)) {
            log.error("starVideo方法：id为null，你让我赞个锤子");
            return Result.fail().message("id为null，你让我赞个锤子");
        }
        Long userId = UserInfo.get();
        String message = videoService.starVideo(id, userId);
        if ("false".equals(message)) {
            log.error("starVideo方法：视频不存在");
            return Result.fail().message("视频不存在");
        } else{
            return Result.succeed().message(message);
        }
    }

    @PostMapping("/history/{id}")
    public Result addHistory(@PathVariable Long id) { // 添加浏览记录，用于兴趣推送去重
        if (ObjectUtils.isEmpty(id)) {
            log.error("addHistory方法：id为null，你让我记录个锤子");
            return Result.fail().message("id为null，你让我记录个锤子");
        }
        Long userId = UserInfo.get();
        videoService.addWatchHistory(id, userId);
        return Result.succeed().message("添加成功");
    }

    @GetMapping("/history")
    public Result getHistory(BasePage basePage) { // 获取用户浏览记录，分页
        return Result.succeed().data(videoService.getHistory(basePage));
    }

    @GetMapping("/favorites/{favoritesId}")
    public Result listVideoByFavorites(@PathVariable Long favoritesId) { // 获取收藏夹下的视频
        if (ObjectUtils.isEmpty(favoritesId)) {
            log.error("listVideoByFavorites方法：favoritesId为null，你让我记录个锤子");
            return Result.fail().message("favoritesId为null，你让我记录个锤子");
        }
        List<Video> videoList = videoService.listVideoByFavorites(favoritesId);
        if (ObjectUtils.isEmpty(videoList)) {
            log.info("listVideoByFavorites方法：id为" + favoritesId + "的收藏夹下没有视频");
        }
        return Result.succeed().data(videoList);
    }

    @PostMapping("/favorites/{fId}/{vId}")
    public Result favoritesVideo(@PathVariable Long fId, @PathVariable Long vId) { // 收藏视频或取消收藏
        String message = videoService.favoritesVideo(fId, vId);
        if ("false".equals(message)) {
            log.error("favoritesVideo方法：收藏夹或视频不存在");
            return Result.fail().message("收藏夹或视频不存在");
        } else{
            return Result.succeed().message(message);
        }
    }

    @GetMapping("/audit/queue/state")
    public Result getAuditQueueState() { // 返回当前审核队列状态
        String  message = videoPublishAuditService.getAuditQueueState() ? "快速" : "慢速";
        return Result.succeed().message(message);
    }

    @GetMapping("/follow/feed")
    public Result followFeed(@RequestParam(required = false) Long lastTime) { //  推送已关注用户发布的视频，拉模式，滚动分页
        Long userId = UserInfo.get();
        List<Video> videoList = videoService.followFeed(userId, lastTime);
        if (!ObjectUtils.isEmpty(videoList)) {
            return Result.succeed().data(videoList);
        } else {
            return Result.fail().message("没有需要推送的视频");
        }
    }

    @PostMapping("/init/follow/feed")
    public Result initFollowFeed() { // // 初始化收件箱，从关注的用户的发件箱中获取数据，记录的是videoId
        Long userId = UserInfo.get();
        // 获取用户的关注列表
        List<Long> followList = followService.getFollowList(null, userId); // 不用分页
        // 初始化用户收件箱
        feedService.initFollowFeed(userId, followList);
        return Result.succeed().message("成功初始化");
    }
}
